
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "xlx_thread.h"
#include "xlx_define.h"

static const char* TAG = "Thread";

static int g_thread_idx = 0;

static TutuThreadHandle * tututhread_new(int stacksize, const char *name, int priority, OnTutuThreadCB cb){
    char namebuf[32]={0};
    int ret = 0;
    TutuThreadHandle *handle = (TutuThreadHandle*)TUTUAlloc(sizeof(TutuThreadHandle));
    handle->thread = NULL;
    handle->cb = cb;

    if (name == NULL) {     // 不输入名字自动命名
        g_thread_idx++;
        sprintf(namebuf, "task_%d", g_thread_idx);
    } else {
        sprintf(namebuf, "%s", name);
    }

    if (priority > configMAX_PRIORITIES) {
        priority = configMAX_PRIORITIES / 2;
    }

    if(handle){
        ret = xTaskCreate(cb, namebuf, stacksize, NULL, priority, &(handle->thread));    
        
        if(ret == pdTRUE) {
            if(handle->thread == NULL){
                TUTU_LOGE(TAG, "new task ERROR! %s() line:%d %s(ret=%d)",__FUNCTION__,__LINE__,namebuf,ret);
                TUTUFree(handle);
                return NULL;
            }
            else{
                TUTU_LOGI(TAG, "new task, %s() line:%d %s(ret=%d)",__FUNCTION__,__LINE__,namebuf,ret);
            }
        }
        else{
            TUTU_LOGE(TAG, "new task ERROR! %s() line:%d %s(ret=%d)",__FUNCTION__,__LINE__,namebuf,ret);
            TUTUFree(handle);
        }
    }
    
    return handle; 
}

//释放线程
static void tututhread_free(TutuThreadHandle *handle){
    if(handle){
        if(handle->thread){
            vTaskDelete(handle->thread);        // 如果用往此函数里面填的任务ID是NULL，即数值0的话，那么删除的就是当前正在执行的任务，此任 务被删除后，FreeRTOS会切换到任务就绪列表里面下一个要执行的最高优先级任务
        }
        TUTUFree(handle);
    }
}


//初始化
void TutuThread_Init(TutuThread *myself){
    TUTU_LOGI(TAG, "%s(%d)", __FUNCTION__, __LINE__); 
    myself->new_thread = tututhread_new;
    myself->free_thread = tututhread_free;
}